package com.duoec.dw.lineage.service.analyser.statement;

import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.statement.SQLSelect;
import com.alibaba.druid.sql.ast.statement.SQLSelectQuery;
import com.alibaba.druid.sql.ast.statement.SQLSelectStatement;
import com.alibaba.druid.sql.ast.statement.SQLWithSubqueryClause;
import com.duoec.dw.lineage.dto.MultiTableLineageDto;
import com.duoec.dw.lineage.dto.TableLineageDto;
import com.duoec.dw.lineage.enums.StatementType;
import com.google.common.collect.Sets;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * @author xuwenzhen
 */
@Service
public class SelectStatementAnalyser extends BaseStatementAnalyser<SQLSelectStatement> {
    @Override
    public Set<Class<? extends SQLStatement>> parseSqlStatements() {
        return Sets.newHashSet(SQLSelectStatement.class);
    }

    @Override
    public TableLineageDto analyse(SQLSelectStatement statement) {
        SQLSelect select = statement.getSelect();
        SQLSelectQuery query = select.getQuery();

        SQLWithSubqueryClause withSubQuery = select.getWithSubQuery();
        MultiTableLineageDto withAsTableLineages;
        if (withSubQuery != null) {
            withAsTableLineages = hiveAnalyser.analyseFrom(withSubQuery, null);
        } else {
            withAsTableLineages = new MultiTableLineageDto();
        }

        TableLineageDto result = hiveAnalyser.analyseQuery(query, withAsTableLineages);

        result.setStatementType(StatementType.SELECT_TABLE);
        return result;
    }
}
